<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2024待办事项</title>
    <link rel="stylesheet" href="css/tasklist.css" />
    <script src="js/vue.global.js"></script>
  </head>
  <!-- 
  1: 引入 Vue，建好Vue代码框架
  2: 数据抽象; 绑定数据；增加事件处理
  3: 任务条目效果和处理
 -->
  <body>
    <div id="app">
      <header>
        <h1>2024待办事项</h1>
        <form id="new-task-form">
          <!-- Step 2 -->
          <input
            type="text"
            v-model="task"
            id="new-task-input"
            placeholder="把计划写下来吧?"
          />
          <input
            type="submit"
            id="new-task-submit"
            placeholder="Add Task"
            @click.prevent="handleAdd()"
          />
        </form>
      </header>
      <main>
        <section class="task-list">
          <h2>任务列表</h2>
          <div id="tasks">
            <!-- Step 3 -->
            <template v-for="(item, index) in tasks">
              <div class="task">
                <div class="content">
                  <input
                    type="text"
                    class="text"
                    v-model="item"
                    :disabled="readonly[index]"
                  />
                </div>
                <div class="actions">
                  <!-- Step 3 -->
                  <button class="edit" @click="handleEdit($event, item, index)">
                    {{btnName[index]}}
                  </button>
                  <!-- Step 1 -->
                  <button class="delete" @click="handleDelete(index)">
                    Delete
                  </button>
                </div>
              </div>
            </template>
          </div>
        </section>
      </main>
    </div>
    <script>
      const rootComponent = {
        data() {
          return {
            tasks: [],
            task: "",
            // Step 4
            btnName: [],
            readonly: [],
          };
        },
        methods: {
          handleAdd() {
            if (this.task) {
              this.tasks.push(this.task);
              this.task = "";
              this.btnName.push("编辑");
              this.readonly.push(true);
            }
          },
          // Step 2
          handleDelete(index) {
            this.tasks.splice(index, 1);
          },
          // Step 5
          handleEdit($event, item, index) {
            console.log($event, item, index);

            if (this.btnName[index] === "编辑") {
              this.btnName[index] = "保存";
              this.readonly[index] = !this.readonly[index];
            } else {
              this.tasks[index] = item;
              this.btnName[index] = "编辑";
              this.readonly[index] = !this.readonly[index];
              return;
            }
          },
        },
      };
      const App = Vue.createApp(rootComponent);
      App.mount("#app");
    </script>
  </body>
</html>
